package fun.liuyu2783.dtc.goods.config;

import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Bean
    public DataSource hikariDataSource(DataSourceProperties dataSourceProperties) {
        /*
         * 打开boot的默认数据源Hikari，可以看到  HikariDataSource dataSource = createDataSource(properties, HikariDataSource.class);
         * 进入 createDataSource 方法，可以看到boot就是使用的dataSourceProperties来创建的数据源，
         * properties.initializeDataSourceBuilder().type(type).build();
         * */
        // 也使用boot默认的数据源
        Class<? extends DataSource> type = HikariDataSource.class;
        HikariDataSource dataSource = (HikariDataSource) dataSourceProperties.initializeDataSourceBuilder().type(type).build();
        if (StringUtils.hasText(dataSourceProperties.getName())) {
            dataSource.setPoolName(dataSourceProperties.getName());
        }
        // 将数据源用seata代理包装，返回自定义的代理数据源
        DataSourceProxy dataSourceProxy = new DataSourceProxy(dataSource);
        return dataSourceProxy;
    }
}
